package com.carpedil.smvc.filter;

import com.carpedil.smvc.po.Permissions;
import com.carpedil.smvc.po.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/** @author Administrator */
// @WebFilter(filterName = "UrlFilter", urlPatterns = "/*")
public class UrlFilter implements Filter {
  @Override
  public void destroy() {
    // ...
  }

  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
      throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    String uri = request.getRequestURI();
    System.out.println("uri = " + uri);
    boolean isAuth = false;
    // 排除放行的资源
    if (uri.endsWith(".html")
        || uri.endsWith(".css")
        || uri.endsWith(".js")
        || uri.endsWith(".png")
        || uri.endsWith(".jpg")
        || uri.endsWith(".gif")
        || uri.endsWith(".jsp")) {
      chain.doFilter(req, resp);
    } else {
      if (uri.contains("login")) {
        chain.doFilter(req, resp);
      } else {
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("loginUser");
        if (obj != null) {
          User user = (User) obj;
          List<Permissions> permissions = user.getPermissions();
          for (Permissions p : permissions) {
            if (p.getModuleUrl().equalsIgnoreCase(uri)) {
              isAuth = true;
              break;
            }
          }

          if (isAuth) {
            chain.doFilter(req, resp);
          } else {
            session.removeAttribute("loginUser");
            response.sendRedirect("/day06_SpringMvcDemo2/index.jsp");
          }

        } else {
          response.sendRedirect("/day06_SpringMvcDemo2/index.jsp");
        }
      }
    }

    chain.doFilter(req, resp);
  }

  @Override
  public void init(FilterConfig config) throws ServletException {
    // ...
  }
}
